namespace ContosoUniversity.Services.QueryServices
{
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Models;
    using NRepository.Core.Query;

    public class StudentControllerQueryService : IStudentControllerQueryService
    {
        private readonly IQueryRepository _QueryRepository;

        public StudentControllerQueryService(IQueryRepository queryRepository)
        {
            _QueryRepository = queryRepository;
        }

        public async Task<IEnumerable<Student>> GetAllStudents(string sortOrder, string searchString)
        {
            var orderStrategy = default(IQueryStrategy);
            switch (sortOrder)
            {
                case "name_desc":
                    orderStrategy = new OrderByDescendingQueryStrategy<Student>(p => p.LastName);
                    break;
                case "Date":
                    orderStrategy = new OrderByQueryStrategy<Student>(p => p.EnrollmentDate);
                    break;
                case "date_desc":
                    orderStrategy = new OrderByDescendingQueryStrategy<Student>(p => p.EnrollmentDate);
                    break;
                default:  // Name ascending 
                    orderStrategy = new OrderByQueryStrategy<Student>(p => p.LastName);
                    break;
            }

            // Fully testable query using InMemoryRecordedRepository and events.
            var students = _QueryRepository.GetEntitiesAsync<Student>(
                new MultipleTextSearchSpecificationStrategy<Student>(
                    "searchString",
                    p => p.LastName,
                    p => p.FirstMidName).OnCondition(!string.IsNullOrEmpty(searchString)),
                orderStrategy);

            return await students;
        }

        public async Task<Student> GetStudentAsync(int studentId)
        {
            return await _QueryRepository.GetEntityAsync<Student>(p => p.ID == studentId, false);
        }
    }
}
